package com.gene.tlonpo.service.remote.common.handler;

import com.gene.tlonpo.service.handler.BusinessHandler;
import com.gene.tlonpo.service.handler.TlonpoBusinessHandler;
import com.gene.tlonpo.service.remote.common.model.DataDto;
import com.gene.tlonpo.service.remote.common.model.DataRespDto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author geneX
 * 服务端业务处理器
 */
@Slf4j
public class TlonpoNettyServerHanlder extends ChannelInboundHandlerAdapter {

    private static BusinessHandler tlonpoBusinessHandler = TlonpoBusinessHandler.tlonpoBusinessHandler;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("[tlonpo server]:client->server new connection,{}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("[tlonpo server]:client->server connection disconnectioned,{}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //业务处理
        if (msg instanceof DataDto) {
            DataDto dataDto = (DataDto) msg;
            DataRespDto dataRespDto = tlonpoBusinessHandler.localCallback(dataDto.getBizKey());
            if (dataRespDto.hasSuccess()){
                dataRespDto.setBackData(dataDto);
            }
            ctx.channel().write(dataRespDto);
        } else {
            log.warn("[tlonpo server]:request error: request data is not data of expect。。。");
            DataRespDto fail = DataRespDto.fail("request error: request data is not data of expect");
            ctx.channel().write(fail);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.channel().flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //异常消息响应回客户端
        log.warn("[tlonpo server]:tlonpo server exception,client address:{}", ctx.channel().remoteAddress(), cause);
        DataRespDto fail = DataRespDto.fail(cause.getMessage());
        ctx.channel().writeAndFlush(fail);

    }
}
